const dayjs = require('dayjs');

// 获取当前时间
type TimeParam = 'YYYY-MM-DD' | 'YYYY-MM-DD HH:mm:ss';
export const getCurrentTime = (formatter: TimeParam): string => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份补零
  const day = String(now.getDate()).padStart(2, '0'); // 日期补零
  const hours = String(now.getHours()).padStart(2, '0'); // 小时补零
  const minutes = String(now.getMinutes()).padStart(2, '0'); // 分钟补零
  const seconds = String(now.getSeconds()).padStart(2, '0'); // 秒补零

  if (formatter === 'YYYY-MM-DD') {
    return `${year}-${month}-${day}`;
  }
  if (formatter === 'YYYY-MM-DD HH:mm:ss') {
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
};

// 随机生成 6 位不同的数字
export function generateUniqueSixDigitNumber() {
  // 获取当前时间戳
  const timestamp = Date.now();
  // 生成一个0到999999之间的随机整数
  const randomNum = Math.floor(Math.random() * 1000000);
  // 将时间戳与随机数组合，并取最后6位
  const uniqueNumber = (timestamp + randomNum) % 1000000;
  // 如果结果小于100000，则在前面补零以保证6位长度
  return uniqueNumber.toString().padStart(6, '0');
}

export function checkEmailOrPhone(str: string) {
  const input = String(str).trim();

  // 邮箱正则：支持字母、数字、常用特殊字符
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (emailRegex.test(input)) {
    return 'email';
  }

  // 手机号处理：移除非数字字符
  const cleanedPhone = input.replace(/[^\d]/g, '');

  // 中国手机号正则（11位，以1开头，第二位为3/4/5/7/8/9）
  const phoneRegex = /^1[345789]\d{9}$/;
  if (phoneRegex.test(cleanedPhone)) {
    return 'telephone';
  }

  // 其他情况
  return 'other';
}

/**
 * 检索数组中是否含有 keyName
 */
export const searchKeyName = <T = any>(
  target: Array<T>,
  keyName: string,
  value: string,
): Array<T> => {
  const result: Array<T> = [];
  target.forEach((item) => {
    if (item[keyName].includes(value)) {
      result.push(item);
    }
  });
  return result;
};

/**
 * 将数组转为字符串
 */
export const toString = (arr: any[]): string => {
  return arr.join('-');
};

/**
 * 将字符串转为数组
 */
export const toArray = (str: string): any[] => {
  return str.split('-');
};

/**
 * 生成 token
 */
export const generateToken = (id: number) => {
  return `xfxj${id}`;
};

/**
 * 添加时间字段
 */
export const addTimeFields = <T>(
  data: T,
): T & {
  createdAt: string;
  updatedAt: string;
} => {
  const currentTime = getCurrentTime('YYYY-MM-DD HH:mm:ss');
  return {
    ...data,
    createdAt: currentTime,
    updatedAt: currentTime,
  };
};

/**
 * 格式化时间
 */
export const formatTime = (
  target: any,
  keys: Array<string>,
  temp = 'YYYY-MM-DD HH:mm:ss',
) => {
  for (const key in target) {
    if (keys.includes(key)) {
      target[key] = dayjs(target[key]).format(temp);
    }
  }
};

/**
 * 拷贝对象属性
 */
export const beanCopy = <V>(vo: V, entity: any): V => {
  const result: V = {} as V;
  const voKeys = Object.keys(vo);
  for (const entityKey in entity) {
    if (voKeys.includes(entityKey)) {
      result[entityKey] = entity[entityKey];
    }
  }
  return result;
};

/**
 * 拷贝数组对象属性
 */
export const beanCopyArray = <V>(vo: V, entity: any[]): V[] => {
  const result: V[] = [];
  entity.forEach((ent: any) => {
    result.push(beanCopy(vo, ent));
  });
  return result;
};
